'''
https://leetcode.cn/problems/average-of-levels-in-binary-tree/?envType=study-plan-v2&envId=top-interview-150
'''
from collections import deque
from typing import List


# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
class Solution:
    def averageOfLevels(self, root: TreeNode) -> List[float]:
        res = []
        q = deque([root])
        while q:
            sum, cnt = 0, 0
            for _ in range(len(q)):
                node = q.popleft()
                sum += node.val
                cnt += 1
                if node.left: q.append(node.left)
                if node.right: q.append(node.right)
            res.append(sum / cnt)
        return res
